package com.chcit.mobile.mvp.inventory.fragment.move;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.mvp.entity.MovementPlanBean;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.chcit.mobile.mvp.inventory.di.component.DaggerMovementPlanDetailComponent;
import com.chcit.mobile.mvp.inventory.contract.MovementPlanDetailContract;
import com.chcit.mobile.mvp.inventory.presenter.MovementPlanDetailPresenter;

import com.chcit.mobile.R;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.toast.XToast;

import java.math.BigDecimal;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

public class MovementPlanDetailFragment extends ScanFragment<MovementPlanDetailPresenter> implements MovementPlanDetailContract.View {

    private MovementPlanBean movementPlanBean;

    @BindView(R.id.tv_movement_plan_detail_productName)
    TextView tvProductName;
    @BindView(R.id.tv_movement_plan_detail_productSpec)
    TextView tvProductSpec;
    @BindView(R.id.tv_movement_plan_detail_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_movement_plan_detail_lot)
    TextView tvLot;
    @BindView(R.id.tv_movement_plan_detail_guaranteeDate)
    TextView tvGuaranteeDate;
    @BindView(R.id.tv_movement_plan_detail_qtyPlan)
    TextView tvQtyPlan;
    @BindView(R.id.tv_movement_plan_detail_qtyMoved)
    TextView tvQtyMoved;
    @BindView(R.id.et_movement_plan_detail_qtyMoving)
    AppCompatEditText etQtyMoving;
    @BindView(R.id.tv_movement_plan_detail_qtyLeft)
    TextView tvQtyLeft;
    @BindView(R.id.tv_shipment_detail_uom)
    TextView tvUom;
    @BindView(R.id.tv_movement_plan_detail_locator)
    TextView tvLocator;
    @BindView(R.id.bt_movement_plan_detail_ok)
    Button btOk;

    public static MovementPlanDetailFragment newInstance(MovementPlanBean movementPlanBean) {
        MovementPlanDetailFragment fragment = new MovementPlanDetailFragment();
        fragment.movementPlanBean = movementPlanBean;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMovementPlanDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_movement_plan_detail, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        setData();
    }

    @SuppressLint("SetTextI18n")
    private void setData() {
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            assert mPresenter != null;
            if (mPresenter.isError) {
                setFragmentResult(RESULT_OK, new Bundle());
            }
            pop();
        });

        tvProductName.setText(movementPlanBean.getProductName());
        tvProductSpec.setText(movementPlanBean.getProductSpec());
        tvManufacturer.setText(movementPlanBean.getManufacturer());
        tvLot.setText(movementPlanBean.getLot());
        tvGuaranteeDate.setText(movementPlanBean.getGuaranteeDate());
        tvUom.setText(movementPlanBean.getUomName());

        tvQtyPlan.setText((movementPlanBean.getQtyPlaned().intValue() + ""));
        tvQtyMoved.setText((movementPlanBean.getQtyConfirmed().intValue() + ""));
        etQtyMoving.setText("0");
        tvQtyLeft.setText((movementPlanBean.getQtyLeft().intValue() + ""));

        tvLocator.setText(movementPlanBean.getToLocatorValue());

        btOk.setEnabled(false);

        etQtyMoving.addTextChangedListener(new TextWatcher() {
            String beforeText;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doAfterTextChanged(s, beforeText, etQtyMoving, tvQtyLeft);
            }
        });
    }

    private void doAfterTextChanged(Editable s, String beforeText, EditText nowEdit, TextView newText) {
        String data = s.toString();
        if (nowEdit.hasFocus() && !data.equals(beforeText)) {
            try {
                BigDecimal movingQty = new BigDecimal(0);
                if (!data.isEmpty()) {
                    movingQty = new BigDecimal(data);
                }
                BigDecimal number = movementPlanBean.getQtyPlaned()
                        .subtract(movementPlanBean.getQtyConfirmed())
                        .subtract(movementPlanBean.getQtyCancelled())
                        .subtract(movingQty);
                if (number.intValue() < 0) {
                    DialogUtil.showErrorDialog(getContext(), "移库数量必须小于等于待移库数量！");
                    nowEdit.setText(beforeText);
                    return;
                }
                newText.setText((number + ""));

                if (movingQty.intValue() > 0) {
                    btOk.setEnabled(true);
                } else {
                    btOk.setEnabled(false);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {

    }

    @OnClick({R.id.bt_movement_plan_detail_ok})
    public void onViewClicked(View view) {
        BigDecimal qtyLeft = new BigDecimal(Objects.requireNonNull(tvQtyLeft.getText()).toString());
        if(qtyLeft.intValue() > 0) {
            String message = "<font color='#FF0000'>该任务要求的数量尚未完成，是否确认移库？</font>";
            MaterialDialog materialDialog =  new MaterialDialog.Builder(mContext)
                    .title("确认移库")
                    .content(Html.fromHtml(message))
                    .positiveText("是")
                    .negativeText("否")
                    .onPositive((dialog, which) -> {
                        doConfirm();
                    })
                    .build();
            materialDialog.getActionButton(DialogAction.POSITIVE).setTextSize(18);
            materialDialog.getActionButton(DialogAction.NEGATIVE).setTextSize(18);
            materialDialog.show();
        }else {
            doConfirm();
        }

    }

    private void doConfirm() {
        int movementPlanId = movementPlanBean.getMovementPlanId();
        int movementPlanLineId = movementPlanBean.getMovementPlanLineId();
        String qtyConfirm = new BigDecimal(Objects.requireNonNull(etQtyMoving.getText()).toString()).toString();;
        String qtyCancel =  new BigDecimal(Objects.requireNonNull(tvQtyLeft.getText()).toString()).toString();;

        JSONObject params = new JSONObject();
        params.put("movementPlanLineId", movementPlanLineId);
        params.put("qtyConfirm", qtyConfirm);
        params.put("qtyCancel", qtyCancel);

        JSONArray lineData = new JSONArray();
        lineData.add(params);

        JSONObject data = new JSONObject();
        data.put("movementPlanId", movementPlanId);//
        data.put("lineData", lineData);

        assert mPresenter != null;
        mPresenter.movePlanConform(data, () -> {
            showMessage("处理成功");
            setFragmentResult(RESULT_OK, new Bundle());
            pop();
        });
    }
}
